﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Hosting;
using NLog;
using OL.FrameCore.Application;
using OL.FrameCore.Application.SysLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace OL.FrameCore.WebUI.Code
{
    /// <summary>
    /// 全局异常处理
    /// </summary>
    public class GlobalExceptionFilter : IExceptionFilter
    {
        ILogger logger = LogManager.GetCurrentClassLogger();
        private readonly IWebHostEnvironment _env;
        private readonly ISysLogService _sysLogService;
        private readonly IHttpContextAccessor _httpContextAccessor;
        public GlobalExceptionFilter(IWebHostEnvironment env, ISysLogService sysLogService, IHttpContextAccessor httpContextAccessor)
        {
            _env = env;
            _sysLogService = sysLogService;
            _httpContextAccessor = httpContextAccessor;
        }

        public void OnException(ExceptionContext context)
        {
            //记录日志
            logger.Error(context.Exception.ToString());

            try
            {
                string msg = context.Exception.Message;
                if (msg.Length > 500)
                    msg = msg.Substring(0, 498) + "..";
                string ip = this._httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
                string userId = "";
                if (context.HttpContext.User != null && context.HttpContext.User.Claims != null && context.HttpContext.User.Claims.Count()>0)
                {
                    var claim = context.HttpContext.User.Claims.Where(c => c.Type == ClaimTypes.Sid).Single();
                    if (claim != null)
                        userId = claim.Value;
                }
                _sysLogService.LogError(new Application.SysLog.Dto.LogErrorRequest
                {
                    ErrorInfo = msg,
                    IP = ip,
                    UserId = userId,
                    CreateTime = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
            }

            if (_env.IsDevelopment())//开发环境
            {
                //throw context.Exception;
            }
            //else//非开发环境
            //{ }

            bool isAjaxCall = context.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest";
            if (isAjaxCall)
            {
                //返回统一格式结果
                var result = new ErrorResult(context.Exception.Message);
                context.Result = new OkObjectResult(result);//返回异常数据
            }
            else
            {
                //跳转错误页

            }
        }
    }
}
